package com.example.simple;

import com.example.CommonMethod;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class Server implements Runnable {


    private Selector selector;


    public Server(Integer port) {
        try {
            selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    processor(iterator.next());
                    iterator.remove();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void processor(SelectionKey selectionKey) {
        if (selectionKey.isAcceptable()){
            registry(selectionKey);
        }else if (selectionKey.isReadable()){
            CommonMethod.read(selectionKey);
        }else if (selectionKey.isWritable()){
            CommonMethod.write(selectionKey);
        }
    }

    private void registry(SelectionKey selectionKey){
        try {
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selectionKey.selector(),SelectionKey.OP_READ);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
